package com.huwei.controller.valid;

import java.util.Objects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Errors;

@Aspect
@Configuration
public class ParamterValidationProxy {
	
	@Around("execution (* *.*.controller.*.*(..))")
	public Object validation(ProceedingJoinPoint pjp) throws Throwable {
		Object[] args = pjp.getArgs();
		if(args.length == 0) {
			return pjp.proceed();
		}
		
		Errors errors = findErrors(args);
		if(Objects.nonNull(errors) && errors.hasErrors()) {
			throw new RequestParamterError(errors);
		}
		
		return pjp.proceed(args);
	}

	private Errors findErrors(Object[] args) {
		for(int i = args.length -1 ; i >=0 ;--i) {
			if(args[i] instanceof Errors) {
				return (Errors) args[i];
			}
		}
		return null;
	}
}
